package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.ConstantUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //管理员登录
    public String login(String username, String password, String code, String uuid) {
        //1、比较输入的验证码和redis中的验证码是否一致
        String key = Constants.CAP_CODE+uuid;
        String redisCode = redisTemplate.opsForValue().get(key);
        //2、如果不一致，抛出一个自定义异常
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key) ;//删除验证码
        //3、根据用户名查询管理员对象 Admin
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //4、判断Admin是否存在,比较输入的密码和数据库密码是否一致
        //需要对用户输入的密码加密 ：明文
        password = SecureUtil.md5(password);//md5加密
        if(admin == null || !password.equals(admin.getPassword())) {
            //5、密码不一致，抛出异常
            throw new BusinessException("用户名或者密码错误");
        }
        //6、生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",admin.getUsername());
        return  JwtUtils.getToken(tokenMap);
    }

    /**
     * 登出
     * @param token
     * @return
     */
    public Map logout(String token) {
        //删除redis的缓存状态
        redisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
        return null;
    }

    //查询当前管理员信息
    public AdminVo profile() {
        //1、获取管理员id
        Long id = AdminHolder.getUserId();
        //2、查询管理员对象
        Admin admin = adminMapper.selectById(id);
        //3、转化vo
        return AdminVo.init(admin);
    }
}
